from datetime import datetime
import json
from app import db

class DataSource(db.Model):
    """数据源模型"""
    __tablename__ = 'data_sources'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
    type = db.Column(db.String(20), nullable=False)  # excel, csv, json, mysql, api等
    config = db.Column(db.Text, default='{}')  # 连接配置，JSON格式
    description = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __repr__(self):
        return f'<DataSource {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'project_id': self.project_id,
            'type': self.type,
            'config': json.loads(self.config) if self.config else {},
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }
    
    def save(self):
        """保存到数据库"""
        db.session.add(self)
        db.session.commit()
    
    def delete(self):
        """从数据库删除"""
        db.session.delete(self)
        db.session.commit()
    
    def get_config_dict(self):
        """获取配置字典"""
        try:
            return json.loads(self.config) if self.config else {}
        except json.JSONDecodeError:
            return {}
    
    def set_config_dict(self, config_dict):
        """设置配置字典"""
        self.config = json.dumps(config_dict)
        db.session.commit()